package android.vn.denguocdemo;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {

	private Button btnDem;
	private TextView tvDem;
	private int mTime = 50;
	private DemNguocRunnable mDemnguocRun;
	private Handler mDemnguocHandler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		btnDem = (Button) findViewById(R.id.btnDem);
		tvDem = (TextView) findViewById(R.id.tvDem);
		btnDem.setOnClickListener(this);
		mDemnguocHandler = new Handler();
		mDemnguocRun = new DemNguocRunnable();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	private void showDemNguoc() {
		mTime=50;		
		mDemnguocHandler.removeCallbacks(mDemnguocRun);
		mDemnguocHandler.postDelayed(mDemnguocRun, 1000);
	}

	private class DemNguocRunnable implements Runnable {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			handleDemnguoc();
		}

	}

	private void handleDemnguoc() {
		mTime--;
		if (mTime == 0)
			mTime = 50;
		tvDem.setText(mTime + "");
		mDemnguocHandler.postDelayed(mDemnguocRun, 1000);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mDemnguocHandler.removeCallbacks(mDemnguocRun);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btnDem:
			showDemNguoc();
			break;

		default:
			break;
		}
	}

}
